package com.lagou.filter;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;


@Activate(group = {CommonConstants.CONSUMER,CommonConstants.PROVIDER})//指定消费者/生产者
public class TPMonitorFilter implements Filter {

    public static HashMap<String, TreeSet<Dimension>> REQUEST_STATISTICS = new HashMap<>();

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        System.out.println("----------------------Filter开始----------------------");
        Result invoke = null;
        long startTime = System.currentTimeMillis();//开始时间
        invoke = invoker.invoke(invocation);
        long endTime = System.currentTimeMillis();//结束时间
        System.out.println("involved time:" + (endTime - startTime)+"毫秒数");

        String serviceName = invocation.getServiceName();//类全限定路劲
        String methodName = invocation.getMethodName();//方法名

        String key = serviceName + ":" + methodName;

        //对象同步锁
        synchronized (REQUEST_STATISTICS) {
            TreeSet<Dimension> treeSet = REQUEST_STATISTICS.get(key);
            if (treeSet == null) {
                treeSet = new TreeSet<>();
                REQUEST_STATISTICS.put(key, treeSet);
            }
            //赋值
            treeSet.add(new Dimension(endTime - startTime, startTime));
        }
        return invoke;
    }

}
